package com.ja.openchat.ui.chat.remittance;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.ui.me.SetPayPwdFragment;
import com.ja.openchat.views.DigitTextWatcher;
import com.ja.openchat.views.UserAvatarView;
import com.ja.openchat.views.VerificationCodeView;
import com.ja.openchat.views.VerifyPayPasswordDialog;
import com.ja.openchat.views.keyboard.KeyboardUtil;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.remittance.RemittanceInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.core.model.wallet.WalletInfo;

import java.util.Map;

import butterknife.BindView;

public class TransferMoneyActivity extends JaBaseActivity {

    public static void startActivity(Context context, ChatInfo chatInfo){
        Intent intent = new Intent(context, TransferMoneyActivity.class);
        intent.putExtra("conversation", chatInfo);
        context.startActivity(intent);
    }

    @BindView(R.id.transferMoneyEditText)
    EditText transferMoneyEditText;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.user_image)
    UserAvatarView user_image;
    @BindView(R.id.userNameText)
    TextView userNameText;
    @BindView(R.id.transferRemarkEditText)
    EditText transferRemarkEditText;
    private ChatInfo chatInfo;



    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }
    @Override
    protected boolean isHaveEventBus() {
        return true;
    }
    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_transfer_money;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    private KeyboardUtil keyboardUtil;


    @Override
    public void initData() {
        super.initData();
//        toolbar.setBackgroundResource(R.drawable.shape_bg_white_color);
        if(getIntent()!=null){
            chatInfo = getIntent().getParcelableExtra("conversation");
        }
        if(chatInfo==null){
            finish();
            return;
        }
        if(chatInfo.isGroup()){
            user_image.showGroup(chatInfo);
            userNameText.setText(chatInfo.title());
        }else{
            UserInfo userInfo = UserInfo.getUserInfo(chatInfo.userId());
            if(userInfo!=null){
                user_image.showUser(userInfo);
                userNameText.setText(userInfo.displayName());
            }
        }
        keyboardUtil = new KeyboardUtil(this,false);

        transferMoneyEditText.post(new Runnable() {
            @Override
            public void run() {
                transferMoneyEditText.requestFocus();
                keyboardUtil.attachTo(transferMoneyEditText);
            }
        });
        keyboardUtil.setOnOkClick(new KeyboardUtil.OnOkClick() {
            @Override
            public void onOkClick() {
                submit();
            }
        });
        new DigitTextWatcher(transferMoneyEditText){
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);

            }
        };

    }

    private void submit(){
        if(TextUtils.isEmpty(transferMoneyEditText.getText())){
            showErrorTip("请输入转账金额");
            return;
        }
        float price = Float.parseFloat(transferMoneyEditText.getText().toString());
        if(price<=0){
            ToastUtils.showShort("请输入转账金额");
            return;
        }
        RemittanceInfo info = new RemittanceInfo();
        info.chatId = chatInfo.id;
        info.description = transferRemarkEditText.getText().toString();
        info.amount = price;
        info.type = 1;
        info.payee = chatInfo.userId();
        showProgress();
        TelegramManager.getTelegramManager().queryWalletInfo(this, new TgResultBlock<WalletInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, WalletInfo walletInfo) {
                hideProgress();
                if(walletInfo!=null){
                    if(!walletInfo.hasPaymentPassword) {
                        tipSetWalletPaymentPasswordDialog();
                    } else {
                        if(walletInfo.balance<info.amount) {//余额不足
                            ToastUtils.showShort("钱包余额不足，请前往余额中心充值");
                        } else {
                            //输入支付密码
                            showPasswordDialog(info);
                        }
                    }
                }else{
                    ToastUtils.showShort("请求错误，请稍后重试");
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                ToastUtils.showShort("请求超时，请稍后重试");
            }
        });
    }


    //设置支付密码
    private void tipSetWalletPaymentPasswordDialog(){
        new XPopup.Builder(TransferMoneyActivity.this).autoDismiss(true).asConfirm("提示", "尚未设置支付密码，现在去设置？", "取消", "设置", new OnConfirmListener() {
            @Override
            public void onConfirm() {
//                startActivity(new Intent(PostRedPacketActivity.this, SetPayPasswordActivity.class));
                startContainerActivity(SetPayPwdFragment.class.getCanonicalName());
            }
        }, new OnCancelListener() {
            @Override
            public void onCancel() {

            }
        },false).show();

    }

    //输入支付密码
    private void showPasswordDialog(RemittanceInfo info){
        if(info==null){
            return;
        }
        new XPopup.Builder(this)
                .autoOpenSoftInput(true)
                .asCustom(new VerifyPayPasswordDialog(this,String.format("%.2f",info.amount),"转账金额", new VerificationCodeView.OnInputFinishListener() {
                    @Override
                    public void onInputFinish(String text) {
                        info.password = text;
                        sumitPasswork(info);
                    }
                }))
                .show();
    }


    public void sumitPasswork(RemittanceInfo info){
        if(info==null){
            return;
        }
        showProgress();
        TelegramManager.getTelegramManager().createTransferMoney(this, info, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if(obj!=null){
                    if(obj.ok){
                        finish();
                    }else if(400 == obj.errCode){
                        //todo wangyutao
                        ToastUtils.showShort("  余额不足，请千万余额中心充值");
                    }
                    else if(404 == obj.errCode)
                    {
                        new XPopup.Builder(TransferMoneyActivity.this).autoDismiss(true).asConfirm("提示", "支付密码错误，重新输入？", "取消", "确定", new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                showPasswordDialog(info);
                            }
                        }, new OnCancelListener() {
                            @Override
                            public void onCancel() {

                            }
                        },false).show();
                    }else if(501 == obj.errCode){
                        ToastUtils.showShort("对方把你加入了黑名单，不能发红包");
                    }
                    else
                    {
                        ToastUtils.showShort("转账失败，请稍后再试");
                    }
                }else{

                }

            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                ToastUtils.showShort("请求超时，请稍后重试");
            }
        });
    }


}
